﻿#include <QColor>
#include <QBrush>
#include <QPainter>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
#include "dieitem.h"

DieItem::DieItem(DieType dieType, QRectF rect, QGraphicsItem* parent)
    : QGraphicsRectItem(rect, parent),
      m_dieType(dieType),
      m_lastRoll(dieType),
      m_containerItem(0)
{
    QBrush brush;
    switch (m_dieType) {
        case Four:
            brush = QColor(0, 255, 0, 150);
            break;
        case Six:
            brush = QColor(0, 0, 255, 150);
            break;
        case Eight:
            brush = QColor(255, 255, 0, 150);
            break;
        case Ten:
            brush = QColor(255, 0, 255, 150);
            break;
        case Twelve:
            brush = QColor(0, 255, 255, 150);
            break;
        case Twenty:
            brush = QColor(255, 0, 0, 150);
    }
    setBrush(brush);
}


DieItem*
DieItem::create()
{
    DieItem* newDie = new DieItem(m_dieType, boundingRect(), this);
    newDie->setContainerItem(m_containerItem);
    newDie->setPen(QColor(255, 255, 255));
    newDie->setFlag(QGraphicsItem::ItemIsMovable);
    newDie->setZValue(4);
    return newDie;
}

void
DieItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
    QRectF br = boundingRect();
    this->QGraphicsRectItem::paint(painter, option, widget);
    painter->drawText(br, Qt::AlignCenter, QString("%1").arg(m_lastRoll));
}

void
DieItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
    qDebug() << endl << "b1" << pos() << mapToParent(pos()) << mapToScene(pos());
    if (flags() & QGraphicsItem::ItemIsMovable) {
        DieItem* die = dynamic_cast<DieItem*>(parentItem());
        /*
        qDebug() << pos();
        QPointF p = pos();
        setPos(p);
        setPos(80, 80);
        */
        //if (die)
        //    die->create();
        return;
    }
    //DieItem* newDie = create();
    //scene()->addItem(newDie);
    //event->accept();
}

void
DieItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
    DieItem* die = dynamic_cast<DieItem*>(parentItem());
    if (!die)
        return;
    if (flags() & QGraphicsItem::ItemIsMovable) {
        if (collidesWithItem(m_containerItem, Qt::ContainsItemShape)) {
            //setParentItem(m_containerItem);
            setParentItem(0);
            setPos(0, 0);
        } else {
            setPos(die->pos());
        }
    } else {
        DieItem* newDie = create();
        scene()->addItem(newDie);
    }
}

uint
DieItem::roll()
{
    uint value = 1;
    m_lastRoll = value;
    return value;
}

